package com.asia5b.debugapp.createorder

import android.graphics.Bitmap
import android.view.View
import androidx.lifecycle.Observer
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.logic.viewmodel.goods.GoodsSpecDFVM
import com.asia5b.a5mall.middleware.logic.viewmodel.order.OrderPlaceActivityVM
import com.asia5b.a5mall.middleware.model.bean.CheckSmsBean
import com.asia5b.a5mall.middleware.model.bean.GlobalState
import com.asia5b.a5mall.middleware.model.bean.ImageCodeType
import com.asia5b.a5mall.middleware.model.cart.CartAllModel
import com.asia5b.a5mall.middleware.model.cart.TransModel
import com.asia5b.a5mall.middleware.model.goods.Goods2SkuModel
import com.asia5b.a5mall.middleware.model.member.AddressModel
import com.asia5b.a5mall.middleware.model.order.OrderPayModel
import com.asia5b.a5mall.middleware.model.order.TradeType
import com.asia5b.a5mall.middleware.utils.JsonUtil
import com.asia5b.a5mall.middleware.utils.getEventBus
import com.asia5b.debugapp.databinding.ActivityDebugCreateorderBinding
import com.asia5b.debugapp.printJson
import com.google.android.flexbox.FlexboxLayoutManager
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_debug_createorder.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2020/8/7.
 */
class DebugCreateOrderActivity : SimpleActivity<DebugCreateOrderVM, ActivityDebugCreateorderBinding>() {
    override val viewModelClazz: Class<DebugCreateOrderVM>
        get() = DebugCreateOrderVM::class.java

    override fun getDataBinding(): ActivityDebugCreateorderBinding {
        return ActivityDebugCreateorderBinding.inflate(layoutInflater)
    }

    val mDatas = mutableListOf<String>()
    val mAdapter = DebugCreateOrderAdapter(mDatas)
    val mRecyclerView by lazy { rv_debug }

    val map by lazy {
        val map = mutableMapOf<String, Any>()
        //地区id
        map["region_id"] = 1
        map["city_id"] = 232
        //仓库
        map["house_id"] = 12
        //运输方式id
        map["goodscata_id"] = 5
        //地址id
        map["address_id"] = 280
        //付款方式
        map["payment_type"] = "ONLINE"
        //订单支付方式
        map["payment_num"] = 1
        //创建订单来源
        map["client"] = "WAP"
        //购物方式
        map["way"] = "BUY_NOW"
        map
    }


    val goodsSpecDFVM by lazy {
        GoodsSpecDFVM()
    }

    val orderPlaceActivityVM by lazy {
        OrderPlaceActivityVM()
    }


    fun notifyDataSetChanged() {
        mAdapter.notifyDataSetChanged()
        mRecyclerView.scrollToPosition(mDatas.size - 1)
    }

    fun notifyText(text: String) {
        mDatas.add(text)
        notifyDataSetChanged()
    }

    override fun initView() {
        mDataBinding.rvDebug.adapter = mAdapter

        val actionList = mutableListOf<ActionBean>()
        actionList.add(ActionBean().apply {
            name = "登录"
            onClickListener = View.OnClickListener {
                loadImageCode()
            }
        })
        actionList.add(ActionBean().apply {
            name = "购买商品"
            onClickListener = View.OnClickListener {
                buyNum()
            }
        })
        val mAdapter = ActionAdapter(actionList)
        rv_debug_action.layoutManager = FlexboxLayoutManager(this)
        rv_debug_action.adapter = mAdapter
    }

    override fun initEvent() {
    }

    override fun startObserver() {
        mViewModel.loginSuccessResultLiveData.observe(this, Observer {
            if (it) {
                loginSuccessResult()
            } else {
                loadImageCode()
            }
        })
        mViewModel.loadImageCodeLiveData.observe(this, Observer {
            loadImageCodeResult(it)
        })
        mViewModel.sendSmsLiveData.observe(this, Observer {
            sendSmsSuccess(it)
        })
        mViewModel.checkSmsCodeLiveData.observe(this, Observer {
            checkSmsCodeSuccess(it)
        })


        orderPlaceActivityVM.setAddressViewLiveData.observe(this, Observer {
//            setAddressView(it)
        })
        orderPlaceActivityVM.setHouseListLiveData.observe(this, Observer {
//            setHouseList(it)
        })
        orderPlaceActivityVM.setTransferListLiveData.observe(this, Observer {
            setTransferList(it)
        })
        orderPlaceActivityVM.setParamsViewLiveData.observe(this, Observer {
//            setParamsView(it)
        })
        orderPlaceActivityVM.setPriceViewLiveData.observe(this, Observer {
            setPriceView(it)
        })
        orderPlaceActivityVM.userCouponResultLiveData.observe(this, Observer {
            userCouponResult()
        })
        orderPlaceActivityVM.createOrderResultLiveData.observe(this, Observer {
            createOrderResult(it)
        })

        goodsSpecDFVM.addCartLiveData.observe(this, Observer {
            addCartResult()
        })
        goodsSpecDFVM.buyNumLiveData.observe(this, Observer {
            buyNumResult()
        })
        goodsSpecDFVM.getGoodsSkuLiveData.observe(this, Observer {
            getGoodsSkuResult(it)
        })
    }

    override fun initData() {
        loadImageCode()
    }


    /**
     * todo 账号密码登录
     */
    fun login() {
        notifyText("开始登录...")
        mViewModel.userLogin("15880000000", "111111", "1111")
    }

    /**
     * 购买商品
     */
    fun buyNum() {
        val sku_id = 25864
        notifyText("开始购买商品(商品sku_id:${sku_id})...")
        goodsSpecDFVM.buyNum(sku_id, 1)
    }

    /**
     * 创建订单
     */
    fun createOrder() {
        notifyText("开始创建订单...")
        orderPlaceActivityVM.getTrans(map)
                .subscribeOn(Schedulers.io())
                .subscribe {

                }
    }

    fun getOrderDetail() {
        if (mTransportations.size > mTransIdIndex) {
            val transModel = mTransportations[mTransIdIndex]
            notifyText("查询运输方式:${transModel.goodsName}是否有价格")
            map["goodscata_id"] = transModel.id
            orderPlaceActivityVM.getOrderDetail(map)
        }
    }

    fun loginSuccessResult() {
        notifyText("登录完毕...")
        printJson(JsonUtil.anyToJson(UserRepository.getUserInfo())) {
            notifyText(it)
        }
    }

    fun loadImageCodeResult(bitmap: Bitmap) {
        notifyText("加载登录验证码完毕")
        login()
    }

    var loadImageCode = 0

    /**
     * todo 调用验证码
     */
    fun loadImageCode() {
        if (loadImageCode > 3) {
            loadImageCode = 0
            return
        }
        notifyText("加载登录验证码...")
        mViewModel.loadImageCode(ImageCodeType.LOGIN)
        loadImageCode++
    }

    fun sendSmsSuccess(bean: CheckSmsBean) {
    }

    fun checkSmsCodeSuccess(bean: CheckSmsBean) {
    }

    override fun onBackPressed() {
        //按返回键返回桌面
        moveTaskToBack(true)
    }

    fun addCartResult() {
    }

    fun buyNumResult() {
        notifyText("购买商品成功")
        createOrder()
    }

    fun getGoodsSkuResult(it: ArrayList<Goods2SkuModel>) {
    }

    fun setAddressResult(addressModel: AddressModel) {
    }

    fun createOrderResult(tradeSerialNo: String?) {
        notifyText("创建订单成功")
        var pay = OrderPayModel()
        pay.paymentType = GlobalState.PAY_ONLINE
        pay.payPrice = mCartAllModel?.total_price?.total_price ?: 0.0
        pay.tradeType = TradeType.Trade
        pay.sn = "${tradeSerialNo}"
//        Asia5bPayUtils.skipPay(mActivity, pay, WCallBack {
////            if (it) {
////                notifyText("开始付款...")
////            }
////        })
    }

    fun setPriceView(cartAllModel: CartAllModel) {
        if (mTransportations.size > mTransIdIndex) {
            val transModel = mTransportations[mTransIdIndex]

            if ((cartAllModel.total_price?.total_price ?: 0.0) > 0) {
                notifyText("${transModel.goodsName}有价格,可以提交")
                mCartAllModel = cartAllModel
                orderPlaceActivityVM.createOrder(map)
            } else {
                notifyText("${transModel.goodsName}无价格,不能提交,用下一个运输方式继续提交订单")
                mTransIdIndex++
                getOrderDetail()
            }
        }

    }

    val mTransportations = arrayListOf<TransModel>()
    var mTransIdIndex = 0
    var mCartAllModel: CartAllModel? = null
    fun setTransferList(transportations: ArrayList<TransModel>?) {
        notifyText("获取了所有的运输方式")
        mTransIdIndex = 0
        mTransportations.clear()
        mCartAllModel = null
        transportations?.let {
            mTransportations.addAll(transportations)
        }


        getOrderDetail()

    }


    fun userCouponResult() {
    }

    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPayEvent(tradeSerialNo: String) {
        notifyText("付款成功:${tradeSerialNo}")
    }


}